﻿using CustomForm.Common;
using CustomForm.Common.Extensions;
using CustomForm.Entities;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.IO;
using System.Threading.Tasks;

namespace CustomForm.Controllers
{
    public class UploadController : Controller
    {
        private readonly IWebHostEnvironment _hostEnvironment;
        private readonly IFreeSql _sql;

        public UploadController(IWebHostEnvironment hostEnvironment, IFreeSql sql)
        {
            _hostEnvironment = hostEnvironment;
            _sql = sql;
        }

        [HttpGet]
        public IActionResult Avatar(long id, long objectId, UploadType type)
        {
            var model = _sql.Select<Wenjian>().Where(f => f.id == id).ToOne() ?? new Wenjian() { wjlj = "/upload/touxiang/1.jpg" };
            ViewBag.ObjectId = objectId;
            ViewBag.UploadType = type;
            return PartialView(model);
        }

        [HttpPost]
        public async Task<IActionResult> Avatar(long id, long objectId, UploadType type, IFormFile file)
        {
            var display = type.GetDisplayAttribute();
            var wenjian = new Wenjian() { id = id };
            if (file != null && file.Length > 0)
            {
                wenjian.ysmc = file.FileName;
                wenjian.wjlj = $"/upload/{display.Name}/{Path.GetRandomFileName().Replace(".", "dot")}{Path.GetExtension(file.FileName)}";

                if (wenjian.id > 0)
                {
                    await _sql.Update<Wenjian>().SetSource(wenjian).ExecuteAffrowsAsync();
                }
                else
                {
                    wenjian.id = await _sql.Insert<Wenjian>(wenjian).ExecuteIdentityAsync();
                }

                var filePath = Path.Combine(_hostEnvironment.WebRootPath, wenjian.wjlj.TrimStart('/'));
                if (!Directory.Exists(Path.GetDirectoryName(filePath)))
                    Directory.CreateDirectory(Path.GetDirectoryName(filePath));
                using var stream = System.IO.File.Create(filePath);
                await file.CopyToAsync(stream);

                await _sql.Ado.ExecuteNonQueryAsync($"update {display.GroupName} set {display.Name} = @wenjian where id = @id", new { wenjian = wenjian.id, id = objectId });
            }

            return RedirectToAction(nameof(Avatar), new { wenjian.id });
        }

        [HttpPost]
        public async Task<IActionResult> Editor(IFormFile file)
        {
            if (file != null && file.Length > 0)
            {
                var filePath = $"/upload/editor/{Path.GetRandomFileName().Replace(".", "dot")}{Path.GetExtension(file.FileName)}";
                var fullPath = Path.Combine(_hostEnvironment.WebRootPath, filePath.TrimStart('/'));
                if (!Directory.Exists(Path.GetDirectoryName(fullPath)))
                    Directory.CreateDirectory(Path.GetDirectoryName(fullPath));
                using var stream = System.IO.File.Create(fullPath);
                await file.CopyToAsync(stream);

                return Content(filePath);
            }

            return Content("没有上传文件");
        }
    }
}
